//处理日期时间格式
function formateDate(date) {
    //将日期时间字符串转化成日期对象
    date = new Date(date);
    return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
}

//从浏览器的地址栏中获取查询参数
function getUrlParams(name) {
    var paramsAry = location.search.substr(1).split('&');
    //循环数据
    for (var i = 0; i < paramsAry.length; i++) {
        var tmp = paramsAry[i].split('=')
        if (tmp[0] == name) {
            return tmp[1]
        }
    }
    return -1;
}

if (isLogin) {
    $.ajax({
        type: 'get',
        url: '/users/' + userId,
        success: function(response) {
            if (response.avatar) {
                $('.userInfo .avatar').attr('src', response.avatar);
            }
            $('.userInfo .name').html('你好！' + response.nickName + '<i class="fa fa-sign-out loginout"></i>');
        }
    })
    $(document).on('click', '.loginout', function() {
        var isConfirm = confirm('您真的要退出吗？');
        if (isConfirm) {
            $.ajax({
                type: 'post',
                url: '/logout',
                success: function() {
                    location.href = 'admin/login.html'
                },
                error: function() {
                    alert('退出失败')
                }
            })
        }
    })
}
//未登录去登录
$(".aside").on('click', '.userInfo', function() {
    if (!isLogin) {
        location.href = "admin/login.html";
    }
})

//消息提示函数
function prompt(message, style, time) {
    style = (style === undefined) ? 'alert-success' : style;
    time = (time === undefined) ? 1300 : time;
    $('<div>')
        .appendTo('body')
        .addClass('alert ' + style)
        .html(message)
        .show()
        .delay(time)
        .fadeOut();
};

//其他页面点赞按钮被点击
$(document).on('click', '.like', function() {
    prompt('点赞、评论请至推荐详情页...', 'alert-info');
})

//向服务器端发送请求 索要随机推荐数据
$.ajax({
    type: 'get',
    url: '/posts/random',
    success: function(response) {
        let data = response.filter(item => {
            return item.state == 1;
        });
        var randomTpl = `
        {{each data}}
        <li>
            <a href="detail.html?id={{$value._id}}">
              <p class="title">{{$value.title}}</p>
              <p class="reading"><i class="fa fa-fire"></i> {{$value.meta.views}}</p>
              <div class="pic">
                <img src="{{$value.thumbnail}}" alt="">
              </div>
            </a>
          </li>
          {{/each}}
        `;
        var html = template.render(randomTpl, {
            data: data
        });
        $('#randomBox').html(html)
    }
})

// 向服务器端索要最新评论数据
$.ajax({
    type: 'get',
    url: '/comments/lasted',
    success: function(response) {
        let data = response.filter(item => { return item.state == 1 }).slice(0, 8);
        var commentTpl = `
        {{each data}}
        <li>
        <a href="javascript:;">
          <div class="avatar">
            <img src="{{$value.author.avatar}}" alt="">
          </div>
          <div class="txt">
            <p>
              <span>{{$value.author.nickName}}</span>{{$imports.formateDate($value.createAt)}}说:
            </p>
            <p>{{$value.content}}</p>
          </div>
        </a>
      </li>
      {{/each}}
        `;
        var html = template.render(commentTpl, {
            data: data
        });
        $('#commentBox').html(html)
    }
})

//向服务器端索要推荐地区数据
$.ajax({
    type: 'get',
    url: '/categories',
    success: function(response) {
        var navTpl = `
        {{each data}}
        <li>
            <a href="list.html?categoryId={{$value._id}}"><i class="fa {{$value.className}}"></i>{{$value.title}}</a>
        </li>
        {{/each}}
        `;
        var html = template.render(navTpl, {
            data: response
        });
        $('#navBox').html(html);
        $('#topNavBox').html(html)
    }
})

//获取搜索表单，并添加表单提交事件
$('.search form').on('submit', function() {
    //获取到用户在表单中输入的搜索关键字
    var keys = $(this).find('.keys').val();
    //跳转到搜索结果页面 并且将用户输入的搜索关键字传递到搜索结果页面中
    location.href = "/search.html?key=" + keys;
    return false
})